<?php
declare (strict_types=1);

namespace app\Api\controller;

use app\api\model\Agent;
use app\validate\Organ as OrganValidate;
use Exception;
use think\facade\Db;
use think\Request;
use think\Response;
use think\response\Json;

class Organ
{
    /**
     * 显示资源列表
     *
     * @return Response
     */
    public function index(Request $request)
    {
        //
        $params = $request->get();
        $page = (int)$params['pageNum'];
        $pageSize = (int)$params['pageSize'];
        $cache = $request->cache;
        try {
            $if = array();
            if (isset($params['keywords']) && !empty($params['keywords'])) {
                $if[] = ['name', 'like', '%' . $params['keywords'] . '%'];
            }
            if (isset($params['status'])) {
                $if[] = ['status', '=', $params['status']];
            }
            // 根据身份设置查询条件
            if($cache['type']==3){
                $if[] = ['parent_id', '=', $cache['identity_info']['id']];
            }
            $field = ['organ.id', 'organ.name', 'organ.person', 'organ.phone', 'user.mobile', 'organ.status', 'organ.type', Db::raw("FROM_UNIXTIME(organ.create_time, '%Y-%m-%d %H:%i:%s') AS createTime")];
            $roles = Db::name('organ')->alias('organ')->where($if)->join('user', 'user.id = user_id')->field($field)->paginate(['page' => $page, 'list_rows' => $pageSize]);
//            return Db::getLastSql();
            return success([
                'total' => $roles->total(),
                'list' => $roles->items(),
                'current_page' => $roles->currentPage(),
                'last_page' => $roles->lastPage(),
            ]);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param Request $request
     * @return Response
     */
    public function save(Request $request)
    {
        //
        $validate = new OrganValidate();
        $params = $request->post();
        if (!$validate->check($params)) {
            return error([], 9001, $validate->getError());
        } else {
            $cache = $request->cache;
            // 开启事务
            Db::startTrans();
            try {
                // 先创建账号
                $time = time();
                $accountData = array(
                    'mobile' => $params['phone'],
                    'password' => initPassword(),
                    'nickname' => $params['name'],
                    'create_time' => $time,
                    'last_time' => $time,
                    'type' => 3,
                    'role'=> $params['type']==2?6:7
                );
                $accountResult = Db::name('user')->insertGetId($accountData);

                // 查询地区信息
                $area = Db::name('area')->where('code', 'in', $params['area'])->order('level', 'asc')->select()->toArray();
                $insData = array(
                    'name' => $params['name'],
                    'user_id' => $accountResult,
                    'phone' => $params['phone'],
                    'person' => $params['person'],
                    'create_time' => $time,
                    'parent_id' => $params['parent_id'],
                    'status' => $params['status'],
                    'province_code' => $area[0]['code'],
                    'province' => $area[0]['name'],
                    'city_code' => $area[1]['code'],
                    'city' => $area[1]['name'],
                    'district_code' => $area[2]['code'],
                    'district' => $area[2]['name'],
                    'address' => $params['address'],
                    'print_able' => $params['print_able'],
                    'report_able' => $params['report_able'],
                    'select_able' => $params['select_able'],
                    'sign_able' => $params['sign_able'],
                    'type' => $params['type'],
                    'create_user_id' => $cache['id']
                );
                $insResult = Db::name('organ')->insertGetId($insData);
                if ($accountResult && $insResult) {
                    Db::commit();
                    writeLogToDb('创建机构成功', $cache['id'], 1, 'organ.id:' . $insResult);
                    return success(['id' => $insResult]);
                } else {
                    Db::rollback();
                    // 抛出异常
                    throw new \think\Exception('新增机构失败');
                }
            } catch (\Exception $e) {
                Db::rollback();
                writeLogToDb('创建机构失败', $cache['id'], 1, $e->getMessage());
                return error($e->getMessage(), 9005, '新增机构失败');
            }
        }

    }

    /**
     * 显示指定的资源
     *
     * @param    $id
     * @return Response
     */
    public function read($id)
    {
        //
        $insData = Db::name('organ')->where(['id' => $id])->find();
        return success($insData);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param Request $request
     * @param    $id
     * @return Response
     */
    public function update($id, Request $request)
    {
        //
        $params = $request->post();
        $validate = new OrganValidate();
        if (!$validate->check($params)) {
            return error([], 9001, $validate->getError());
        } else {
            $cache = $request->cache;
            // 开启事务
            Db::startTrans();
            try {
                // 先创建账号
                $time = time();
                // 查询机构的信息
                $organData = Db::name('organ')->find($params['id']);
                // 查询地区信息
                $area = Db::name('area')->where('code', 'in', $params['area'])->order('level', 'asc')->select()->toArray();
                $insData = array(
                    'id' => $params['id'],
                    'name' => $params['name'],
//                    'phone' => $params['phone'],
                    'type' => $params['type'],
                    'person' => $params['person'],
                    'update_time' => $time,
                    'parent_id' => $params['parent_id'],
                    'status' => $params['status'],
                    'province_code' => $area[0]['code'],
                    'province' => $area[0]['name'],
                    'city_code' => $area[1]['code'],
                    'city' => $area[1]['name'],
                    'district_code' => $area[2]['code'],
                    'district' => $area[2]['name'],
                    'address' => $params['address'],
                    'print_able' => $params['print_able'],
                    'report_able' => $params['report_able'],
                    'select_able' => $params['select_able'],
                    'sign_able' => $params['sign_able'],
                );
                $insResult = Db::name('organ')->update($insData);
                $userData =[
                    'id'=>$organData['user_id'],
                    'nickname'=>$params['name']
                ];
                $userUpdate = Db::name('user')->update($userData);
                if ($insResult !== false && $userUpdate!==false) {
                    Db::commit();
                    writeLogToDb('修改机构成功', $cache['id'], 1, "params:" . json_encode($params));
                    return success(['id' => $insResult]);
                } else {
                    Db::rollback();
                    // 抛出异常
                    throw new \think\Exception('修改机构失败');
                }
            } catch (\Exception $e) {
                Db::rollback();
                writeLogToDb('创建机构失败', $cache['id'], 1, $e->getMessage());
                return error($e->getMessage(), 9005, '修改机构失败');
            }
        }

    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return Response
     */
    public function delete($id)
    {
        //
    }

    /** 查询作为选项使用的机构数据
     * @param Request $request
     * @return void
     */
    public function options(Request $request)
    {
        $if = $this->calcInsIf($request->cache);
        $cache = $request->cache;
        $if[] = [
            'type', '=', 2
        ];
        $insList = Db::name('organ')->where($if)->field('id as value ,name as label')->select()->toArray();
        if($cache['type']==1){
            $insList= array_merge([['value'=>0,'label'=>'考委会']],$insList);
        }
        return success($insList, 0, '', Db::getLastSql());
    }

    /**
     * 根据账号属性获取机构查询条件
     * @param $identity
     * @return array|Json
     */
    private function calcInsIf($identity): Json|array
    {
        $where = [];
        //  判定是管理员还是代理或者机构
        switch ($identity['type']) {
            case 1:
                break;
            case 2:
                $where = [['parent_id', '=', $identity['identity_info']['id']]];
                break;
            case 3:
                $where = [['id', '=', $identity['identity_info']['id']]];
                break;
            default:
                return error([], 9009, '没有权限');
        }

        return $where;
    }
    public function importData(Request $request)
    {
        ini_set('memory_limit', '512M');
        $cache = $request->cache;
        $file = request()->file('file');
        $params = $request->get();
        $allowedExtensions = ['xls', 'xlsx'];
        $filename = $_FILES['file']['name'];
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
        try {
            if (!in_array(strtolower($extension), $allowedExtensions)) {
                throw new Exception('文件格式错误', 9002);
            }
            // 校验是否存在配置
            $filePath = $file->getRealPath();
//            $filePath=public_path().'excel_files/导出花名册.xlsx';
//            echo $filePath;
            // 把表单里面的数据存储入data中
            $data = readExcelToArray($filePath);
            unset($data[0]);
            $userDatas=[];
            $organDatas=[];
            $area  =Db::name('area')->select()->toArray();
            $areaOptions=convertValueToKey($area,'name');
//            return $areaOptions;
            foreach ($data as $index=>$item){
                print_r(extractAddressComponents($item[2]));
                if($index==20){
                    break;
                }
            }
            return $data;
        } catch (\Exception $e) {
            Db::rollback();
            writeLogToDb('导入报名信息失败', $cache['id'], 1, ['message' => $e->getMessage(), 'params' => $request->post('active_id')]);
            return error([], $e->getCode() ?: 9006, $e->getMessage());
        }
    }
}
